<?php 
/* --------------------------------
 * модификации для админ части
 *  
 * 9 августа 2012
 * © Deemon 
 --------------------------------*/
define('is_site',false);
//Расширенный класс выбираемых полей
class Selectable_ extends Selectable
{
	private $load=false;
	private $fields_types=array(
		'select'=>'select',
		'multiselect'=>'multiselect',
		'checkbox'=>'checkbox',
		'multicheckbox'=>'multicheckbox',
		'radio'=>'radio',
		'text'=>'text',
		'datetime'=>'datetime',
		'date'=>'date',
		'textarea'=>'textarea',
		'email'=>'email',
		'number'=>'number'
		);
	private $js_array_added=false;
	private $redirect=false;
	private $control_name='Выбираемое';
	function Selectable_($conn,$group_type,$cache,$load,$params=array())
	{
		$this->cache=&$cache;
		$this->load=&$load;
		/*Префикс таблиц*/
		if(isset($params['table_prefix']))
			$this->table_prefix=$params['table_prefix'];
			
		$this->need_cache=isset($params['need_cache']);
		$this->object_id=!empty($params['object_id'])?$params['object_id']:0;
		$this->redirect=isset($params['redirect'])?$params['redirect']:true;
		$this->query_where=!empty($params['query_where'])?'and '.$params['query_where']:'';
		if(isset($params['control_name']))
			$this->control_name=$params['control_name'];
		$this->group_type=$group_type;
		$this->conn=&$conn;
	}
	function getEdit($can_edit=false)
	{
		
		$prefix_name=$this->prefix.$this->group_type;
		$arr_name=$prefix_name.$this->object_id;
		$arr_name_edit=$arr_name.'edit';
		
		/*Пути для кеша*/
		$cache_user_path='admin/selectable/'.$this->group_type;
		$cache_adm_path=$cache_user_path.'_edit';
			
		$cache=$this->cache->get($cache_adm_path,'edit_selectable',array('group_name'=>$prefix_name,'table_prefix'=>$this->table_prefix));
		
		if(!$cache && !$can_edit)return false;//нет данных и у пользователя нет доступа к добавлению полей 
		$edit='<div class="editor_block form" f_name="'.$arr_name.'" id="selectable">'
			.($can_edit?$this->load->block('form_control',array('controls'=>array('edit','delete'),'title'=>$this->control_name)):'')
		.'<div class="to_save">';
		sessionStart();		
		$value_prototype=$field_prototype='';
		$redirect=false;
		/*Прототипы полей и значений*/
		if($can_edit )
		{			
			/*Прототип добавления значений*/
			$value_prototype=
				$this->load->block('form_element',array('name'=>$arr_name.'[#][fields][@][values][!][val]','desc'=>'Значение'))
				.$this->load->block('form_element',array('name'=>$arr_name.'[#][fields][@][values][!][val_sys]','desc'=>'Cис. значеие'))
				.'<span class="def">'.$this->load->block('form_element',array('type'=>'checkbox','desc'=>'По умолч.','name'=>$arr_name.'[#][fields][@][values][!][def]')).'</span>';
			/*Прототип добавления поля*/
			$field_prototype=
			'<td class="field_name">'
				.$this->load->block('form_element',array('name'=>$arr_name.'[#][fields][@][name]','desc'=>'Название поля'))
				.$this->load->block('form_element',array('name'=>$arr_name.'[#][fields][@][name_sys]','desc'=>'Cис. название'))
			.'</td>
			<td class="type">'
				.$this->load->block('form_element',array('type'=>'select','name'=>$arr_name.'[#][fields][@][type]','desc'=>'Тип поля','values'=>$this->fields_types))
			.'</td>
			<td class="values">
				<div class="value">'
					.$value_prototype.
				'</div>
				<div class="add_prototype value">'
					.$value_prototype.
				'</div>
				'.$this->load->block('buttons',array('style'=>'add','attr'=>'onclick ="form_control_function(this,\'value\',\'!\')" btype="add"','text'=>'Добавить значение')).'
			</td>';
			/*Обработка добавления  и обновления полей*/
			if(!empty($_POST[$arr_name]))
			{
				foreach($_POST[$arr_name] as $g_id=>$group)
				{
					if(is_numeric($g_id))//Обновить
					{
						if(!empty($group['fields']) && !empty($group['group_name']) && !empty($group['group_name_sys']))//есть хоть одно поле и заполнена группа
						{
							$group_id=$g_id;
							$type=mysql_escape_string($prefix_name);
							/*Проверяю принадлежит ли редактируемая группа к данным полям*/
							$this->conn->query("select id from groups where id=$g_id and `type`='$type'");
							if(!$this->conn->rowCount())continue;
							foreach($group['fields'] as $f_id=>$field)
							{
								$field_id=is_numeric($f_id)?$f_id:false;
								/*Проверяю принадлежит ли поле к редактируемой группе*/
								if(!empty($field['values']) && isset($field['type']) && isset($this->fields_types[$field['type']]) && !empty($field['name']) && !empty($field['name_sys']))//есть хоть одно значение и заполнено поле
								{
									if($field_id)//обновляю поле
									{
										$this->conn->query('update '.$this->table_prefix.'_fields set name=\''
											.mysql_escape_string($field['name'])
											.'\',name_sys=\''.mysql_escape_string($field['name_sys'])
											.'\',type=\''.$this->fields_types[$field['type']]
											."' where id=$field_id and group_id=$group_id");
									}
									foreach($field['values'] as $v_id=>$value)
									{
										$one_val=in_array($this->fields_types[$field['type']],array('checkbox','text','textarea','email','number'));
										if ($one_val || (!empty($value['val'])||!empty($value['val_sys'])))//есть не пустое занчение
										{
											if(empty($value['val_sys']) && !empty($value['val']))
												$value['val_sys']=getGoodUrl($value['val']);
											if(!$field_id)
											{
												$field_id=$this->conn->query('insert into '.$this->table_prefix.'_fields (group_id,`type`,name,name_sys)values('
													.$group_id.',\''
													.mysql_escape_string($this->fields_types[$field['type']]).'\',\''
													.mysql_escape_string($field['name']).'\',\''
													.mysql_escape_string($field['name_sys']).'\')',true);
												if(!$field_id) break;
											}
											if(is_numeric($v_id))
											{
												if($field_id)
													$this->conn->query('update '.$this->table_prefix.'_values set value=\''
														.mysql_escape_string($value['val'])
														.'\',value_sys=\''.mysql_escape_string($value['val_sys']).'\',is_default='.(isset($value['def'])?'1':'0')." where field_id =$field_id and id=$v_id");											
											}
											else
												$this->conn->query('insert into '.$this->table_prefix.'_values (field_id,value,value_sys,is_default)values('
													.$field_id.',\''
													.mysql_escape_string($value['val']).'\',\''
													.mysql_escape_string($value['val_sys']).'\','
													.(isset($value['def'])?'1':'0').')');
											if($one_val)break;
										}
									}
									if(!$field_id) break;
									
								}
							}
							$this->conn->query('update groups set name=\''
							.mysql_escape_string($group['group_name'])
							.'\',name_sys=\''
							.mysql_escape_string($group['group_name_sys'])
							."' where id=$group_id and `type`='$type'");
						}
				
					}
					else//Добавить
					{
						if(!empty($group['fields']) && !empty($group['group_name']) && !empty($group['group_name_sys']))//есть хоть одно поле и заполнена группа
						{
							$group_id=false;
							foreach($group['fields'] as $f_id=>$field)
							{
								$field_id=false;
								if(!empty($field['values']) && isset($field['type']) && isset($this->fields_types[$field['type']]) && !empty($field['name']) && !empty($field['name_sys']))//есть хоть одно значение и заполнено поле
								{
									foreach($field['values'] as $v_id=>$value)
									{
										$one_val=in_array($this->fields_types[$field['type']],array('checkbox','text','textarea','email','number'));
										if ($one_val || (!empty($value['val'])||!empty($value['val_sys'])))//есть не пустое занчение
										{
											
											if(empty($value['val_sys']) && !empty($value['val']))
												$value['val_sys']=getGoodUrl($value['val']);
											if(!$group_id)
											{
												$group_id=$this->conn->query('insert into groups(`type`,name,name_sys)values(\''
													.mysql_escape_string($prefix_name).'\',\''
													.mysql_escape_string($group['group_name']).'\',\''
													.mysql_escape_string($group['group_name_sys']).'\')',true);
												if(!$group_id) break;
											}
											if(!$field_id)
											{
												$field_id=$this->conn->query('insert into '.$this->table_prefix.'_fields (group_id,`type`,name,name_sys)values('
													.$group_id.',\''
													.mysql_escape_string($this->fields_types[$field['type']]).'\',\''
													.mysql_escape_string($field['name']).'\',\''
													.mysql_escape_string($field['name_sys']).'\')',true);
												if(!$field_id) break;
											}
											$this->conn->query('insert into '.$this->table_prefix.'_values (field_id,value,value_sys,is_default)values('
												.$field_id.',\''
												.mysql_escape_string($value['val']).'\',\''
												.mysql_escape_string($value['val_sys']).'\','
												.(isset($value['def'])?'1':'0').')');
											if($one_val)break;
										}
										if(!$group_id) break;
									}
									
								}
							}
						}
					}
				}	
				$this->cache->delete($cache_adm_path);
				$this->cache->delete($cache_user_path);
				$redirect=true;		
				}			
		}
		/*Вывод обработка параметров*/
		if(!empty($cache) &&!empty($cache['groups']))
		{
			$groups_ids=implode(',',$cache['groups_ids']);
			
			if( !empty($_POST[$arr_name_edit]))
			{
				/*Удалить*/
				if(isset($_POST[$arr_name_edit]['delete']))
				{
					foreach($_POST[$arr_name_edit]['delete'] as $g_id=>$val)
					{
						/*проверяю правильная ли группа*/
						if(!isset($cache['groups'][$g_id]))
							continue;
						if(is_array($val))
						{
							if(!empty($val))
								foreach($val as $field_id)
									/*Проверяю принадлежат ли поля к данной группе*/
									if(isset($cache['fields_index'][$field_id]))
									{
										/*поля*/
										$this->conn->query("delete from {$this->table_prefix}_fields where id=$field_id ");
										/*допустимые занчения*/
										if(!empty($cache['groups'][$g_id]->fields[$field_id]->values))
										{
											$values=array();
											foreach($cache['groups'][$g_id]->fields[$field_id]->values as $value)
												$values[]=$value->id;
											$values=implode(',',$values);		
											
											$this->conn->query("delete from {$this->table_prefix}_values where id in($values) ");
											/*выбранные значения*/
											$values=" or (value_text!='{$this->text_f}' and value_id in($values))";
											$this->conn->query("delete from {$this->table_prefix}_datas where (value_text='{$this->text_f}' and value_id=$field_id)$values");
										}
									}
							
						}
						else
						{
							$type=mysql_escape_string($prefix_name);
							/*Группу*/
							$this->conn->query("delete from groups where id=$g_id and type='$type'");
							$fields=array();
							if(!empty($cache['groups'][$g_id]->fields))
								foreach($cache['groups'][$g_id]->fields as $field)
									$fields[]=$field->id;
							if(!empty($fields))
							{
								$fields=implode(',',$fields);
								/*поля */
								$this->conn->query("delete from {$this->table_prefix}_fields where id in($fields)");
								//Допустимые занчения
								$this->conn->query("delete from {$this->table_prefix}_values where field_id in($fields)");
							}
							/*Выбранные значения*/
							$this->conn->query("delete from {$this->table_prefix}_datas where group_id=$g_id");
						}
					}
					$this->cache->delete($cache_user_path);
					$this->cache->delete($cache_adm_path);
				}
				elseif(isset($_POST[$arr_name_edit]['groups']))
				{
					$g_ids=implode(',',$_POST[$arr_name_edit]['groups']);
					$this->conn->query("delete from {$this->table_prefix}_datas where group_id in($g_ids) and object_id ={$this->object_id}");
					foreach($_POST[$arr_name_edit] as $field_id=>$val)
					if(isset($cache['fields_index'][$field_id]))//Существующее поле
					{
						$field=false;
						if(isset($cache['groups'][$cache['fields_index'][$field_id]]->fields[$field_id]))
							$field=$cache['groups'][$cache['fields_index'][$field_id]]->fields[$field_id];
						//Выбрано "по умолчанию"
						$def=false;
						
						if($val=='def')
						{
							if(isset($field->defaults))//Есть значение по умолчанию
								 $val=$field->defaults;
							else//значения нет 
								continue; 
							$def=true;
						}
						if(!is_array($val))
							$val=array($val);						
						foreach($val as $v)
						{
							$val_text=$this->text_f;
							if(!in_array($field->type,Selectable::$not_text_types))
							{
								$val_text=mysql_escape_string($def?(isset($field->values[$v])?$field->values[$v]->value:''):$v);
								$v=$field->id;
							}
							elseif((string)$v=='0')
							{
								continue;
							}
							if($field->type=='checkbox')
							{
								$v=array_shift($field->values);
								$v=$v->id;
							}
							$this->conn->query("insert into {$this->table_prefix}_datas(group_id,object_id,value_id,value_text)values({$field->group_id},{$this->object_id},$v,'$val_text') ");
						}
					}					
					$this->cache->delete($cache_user_path);
				}
				$redirect=true;
			}
			$datas=array();
			if(!$redirect)
			{		
				$this->conn->query("select * from {$this->table_prefix}_datas where group_id in ($groups_ids) and object_id={$this->object_id} {$this->query_where} order by group_id");
				while( $data = $this->conn->fetch() )  // Формирую список поле - значения
				{
					if( isset( $cache['values_index'][$data->value_id] ) )
					$datas[$data->value_text == $this->text_f ? $cache['values_index'][$data->value_id] : $data->value_id][] = $data;
				}
			}
			if(!$redirect)
			foreach( $cache['groups'] as $g_id => $group )
			{
				$fields='';
				if(!empty($group->fields))
				foreach( $group->fields as $f_id => $field )
				{
					$values='';
					if(empty($field->values))
						continue;
					foreach( $field->values as $v_id => $value )
					{
						$values.='<div class="value hidden" id="'.$v_id.'">'
							.$this->load->block('form_element',array('class'=>'val','val'=>$value->value,'to_edit'=>true))
							.$this->load->block('form_element',array('class'=>'val_sys','val'=>$value->value_sys,'to_edit'=>true))
							.'<span class="def">'.$this->load->block('form_element',array('val'=>$value->is_default,'type'=>'checkbox','to_edit'=>true)).'</span>
						</div>';
					}
					$field_values=false;
					$field_data_value=false;
					$field_name=$arr_name_edit.'['.$field->id.']';
					switch($field->type)
					{
						/*Много допустимых значений и множественный выбор*/
						case 'multiselect':
						case 'multicheckbox': 
							$field_values=array();
							foreach($field->values as $val)
								$field_values[$val->id]=$val->value;
							$field_data_value=array();							
							if(isset($datas[$field->id]))
								foreach($datas[$field->id] as $data)
									$field_data_value[]=$data->value_id;
							$field_name.='[]';
						break;
						/*Много допустимых значений выбрать можно только одно*/						
						case'select':
						case 'dee-select':
							$field_values=array('');
						case'radio':
							foreach($field->values as $val)
								$field_values[$val->id]=$val->value;
							if(isset($datas[$field->id]))
								$field_data_value=array_shift($datas[$field->id])->value_id;
						break;
						/*одно допустимое значение*/
						case'checkbox':
							$field_data_value=isset($datas[$field->id]);
						break;
						/*текстовое значение*/
						default:
							if(isset($datas[$field->id]))
							{
								$field_data_value=array_shift($datas[$field->id]);
								if($field_data_value->value_text!=$this->text_f)
									$field_data_value=$field_data_value->value_text;
								else 
									$field_data_value=false;
							}
					}
					$fields.='<tr id="'.$f_id.'">
						<td class="field_name">'
							.($can_edit?$this->load->block('form_element',array('type'=>'checkbox','name'=>$arr_name_edit.'[delete]['.$g_id.'][]','value'=>$f_id,'class'=>'delete hidden','attr'=>'title="Удалить поле"')):'')
							.$this->load->block('form_element',array('val'=>$field->name,'class'=>'name','to_edit'=>true))
							.$this->load->block('form_element',array('class'=>'name_sys hidden','val'=>$field->name_sys,'attr'=>'class="hidden"','to_edit'=>true))
						.'</td>
						<td class="type hidden">'
							.$this->load->block('form_element',array('type'=>'select','val'=>$field->type,'values'=>$this->fields_types,'to_edit'=>true))
							
						.'</td>
						<td class="values">'
							.$this->load->block('form_element',array('type'=>$field->type,'val'=>$field_data_value,'values'=>$field_values,'name'=>$field_name))
							.' <span class="def">'.$this->load->block('form_element',array('type'=>'checkbox','desc'=>'По умолч.','name'=>$arr_name_edit.'['.$field->id.']','value'=>'def')).'</span>'
							.$values
						.'</td>
					</tr>';
				}
				$edit.='<div class="prot_parent group" id="'.$g_id.'">
						<div class="group_name">'
							.($can_edit
								?$this->load->block('form_element',array('type'=>'checkbox','name'=>$arr_name_edit.'[delete]['.$g_id.']','class'=>'edit delete','desc'=>$group->name))
								.$this->load->block('form_element',array('val'=>$group->name,'class'=>'name hidden','to_edit'=>true))
								.$this->load->block('form_element',array('val'=>$group->name_sys,'class'=>'hidden name_sys','to_edit'=>true))
								:"<span>{$group->name}</span>")
						.'</div>					
						<table>'
							.$fields
						.'</table>	
					<input type="hidden" name="'.$arr_name_edit.'[groups][]" value="'.$g_id.'" />						
					</div>';
				
			}
			$edit.=$this->load->block('buttons',array('style'=>'ok','type'=>'submit','attr'=>'onclick="fc_deleteProt(this);"','text'=>'Сохранить'));
		}
		if($redirect && $this->redirect) successRedirect();
		/*Прототип группы*/
		if($can_edit)
		{			
			 $edit.='<div class="to_edit add_prototype group">
					<div class="group_name">'
						.$this->load->block('form_element',array('name'=>$arr_name.'[#][group_name]','desc'=>'Название группы'))
						.$this->load->block('form_element',array('name'=>$arr_name.'[#][group_name_sys]','desc'=>'Сис. название'))
					.'</div>					
					<table>
						<tr class="field prot_parent">'
							.$field_prototype
						.'</tr>
						
						<tr class="add_prototype field">'
							.$field_prototype
						.'</tr>
						<tr class="last"><td colspan="4">'
							.$this->load->block('buttons',array('style'=>'add','attr'=>'onclick ="form_control_function(this,\'field\',\'@\')" btype="add"','text'=>'Добавить поле'))
						.'</td></tr>
					</table>
				</div>'
				.$this->load->block('buttons',array('style'=>'add','attr'=>'onclick ="form_control_function(this,\'group\',\'#\');$(this).parents(\'.to_save\').find(\'.group:not(.to_edit),button.ok\').remove();" btype="add"','text'=>'Добавить группу'))
			.'</div>';
		}
		if(!$this->js_array_added)
		{
			$edit.='<script type="text/javascript">var selectable_fields_types='
					.getJSArr($this->fields_types)
				.';</script>';
			$this->js_array_added=true;
		}
		return $edit.'</div>';
	}
}


$configs=new Selectable_($conn,'configs',$cache,$load,array('need_cache'=>true,'control_name'=>'Настройки'));
$configs->elog=&$elog;
$view->templ='_login';
if(isset($_GET['p'])&& $_GET['p']!='')
{
	if($user->allowed('access',$_GET['p']))
		$view->templ=$_GET['p'];
	else if(!isset($_POST['login']['logout']))$view->quickMessage('У вас нет доступа к этому разделу',DEE_ERROR);
	$view->js('admin/store');
}
if(!is_ajax)$view->js('admin/admin');
//Если шаблон страницы не найден по ссылке то вывожу страницу логина
if(!$load->templ())
{
	$view->templ='_login';
	$load->templ();
}